package com.ruoyi.web.controller.storeSettings;

import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLNonTransientException;
import java.sql.Wrapper;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.util.AbdulEmptyUtils;
import com.ruoyi.system.util.StoreIdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.StoreSettings;
import com.ruoyi.system.service.IStoreSettingsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 门店设置Controller
 *
 * @author ruoyi
 * @date 2025-05-07
 */
@Api(tags = "门店设置")
@RestController
@RequestMapping("/system/storeSettings")
public class StoreSettingsController extends BaseController {
    @Autowired
    private IStoreSettingsService storeSettingsService;

    @Autowired
    private StoreIdUtils storeIdUtils;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询门店设置列表
     */
    @ApiOperation("查询门店设置列表")
//    @PreAuthorize("@ss.hasPermi('system:settings:list')")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) String storeName) {
        startPage();
        List<StoreSettings> list = storeSettingsService.selectStoreSettingsListByName(storeName);
        // 直接返回实体列表，利用实体类中的 @JsonProperty 注解
        return getDataTable(list);
    }

    /**
     * 导出门店设置列表
     */
    @ApiOperation("导出门店设置列表")
    @PreAuthorize("@ss.hasPermi('system:settings:export')")
    @Log(title = "门店设置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestParam(required = false) String storeName) {
        List<StoreSettings> list = storeSettingsService.selectStoreSettingsListByName(storeName);
        ExcelUtil<StoreSettings> util = new ExcelUtil<StoreSettings>(StoreSettings.class);
        util.exportExcel(response, list, "门店设置数据");
    }

    /**
     * 通过id获取门店设置详细信息
     */
    @ApiOperation("通过id获取门店设置详细信息")
    @PreAuthorize("@ss.hasPermi('system:settings:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(storeSettingsService.selectStoreSettingsById(id));
    }

    /**
     * 新增门店设置列表
     */
    @ApiOperation("新增门店设置")
    @PreAuthorize("@ss.hasPermi('system:settings:add')")
    @Log(title = "门店设置", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody StoreSettings storeSettings) {
        if (AbdulEmptyUtils.isEmpty(storeSettings.getStoreName())) {
            throw new RuntimeException("门店名称不能为空");
        }
        //新增门店 1-新增部门 2-拿到部门id当作门店id
        List<SysDept> list = sysDeptService.list();
        SysDept sysDept = getSysDept(storeSettings, list);
        sysDeptService.insertDept(sysDept);
        LambdaQueryWrapper<SysDept> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysDept::getDeptName, storeSettings.getStoreName());
        lqw.orderByDesc(SysDept::getCreateTime);
        lqw.last("limit 1");
        SysDept sysDeptServiceOne = sysDeptService.getOne(lqw);

        storeSettings.setStoreId(sysDeptServiceOne.getDeptId());
        LambdaQueryWrapper<StoreSettings> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StoreSettings::getStoreName, storeSettings.getStoreName());
        StoreSettings serviceOne = storeSettingsService.getOne(wrapper);
        if (!AbdulEmptyUtils.isEmpty(serviceOne)) {
            throw new RuntimeException("门店名称已存在");
        }
        return toAjax(storeSettingsService.insertStoreSettings(storeSettings));
    }

    public SysDept getSysDept(StoreSettings storeSettings, List<SysDept> list) {
        if (list.isEmpty()) {
            throw new RuntimeException("请先创建部门");
        }
        Long deptId = 0L;
        for (SysDept sysDept : list) {
            if (sysDept.getParentId() == 0 && sysDept.getStatus().equals("0")) {
                //顶级部门id
                deptId = sysDept.getDeptId();
                break;
            }
        }
        if (deptId==0L){
            throw new RuntimeException("请先创建父级部门");
        }
        SysDept sysDept = new SysDept();
        sysDept.setParentId(deptId);
        sysDept.setDeptName(storeSettings.getStoreName());
        sysDept.setOrderNum(0);
        sysDept.setStatus("0");
        return sysDept;
    }

    /**
     * 修改门店设置
     */
    @ApiOperation("修改门店设置")
    @PreAuthorize("@ss.hasPermi('system:settings:edit')")
    @Log(title = "门店设置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StoreSettings storeSettings) {

        return toAjax(storeSettingsService.updateStoreSettings(storeSettings));
    }

    /**
     * 通过id批量删除门店设置信息
     */
    @ApiOperation("通过id批量删除门店设置信息")
    @PreAuthorize("@ss.hasPermi('system:settings:remove')")
    @Log(title = "门店设置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(storeSettingsService.deleteStoreSettingsByIds(ids));
    }
}
